/**
 * 网络请求封装
 */

const app = getApp();

/**
 * 发起HTTP请求
 * @param {Object} options - 请求配置
 * @returns {Promise}
 */
function request(options) {
  return new Promise((resolve, reject) => {
    const {
      url,
      method = 'GET',
      data = {},
      header = {},
      showLoading = true,
      loadingText = '加载中...'
    } = options;

    // 显示加载提示
    if (showLoading) {
      wx.showLoading({
        title: loadingText,
        mask: true
      });
    }

    // 构建完整URL
    const fullUrl = url.startsWith('http') ? url : `${app.globalData.apiBaseUrl}${url}`;

    // 添加token
    const requestHeader = {
      'Content-Type': 'application/json',
      ...header
    };

    if (app.globalData.token) {
      requestHeader['Authorization'] = `Bearer ${app.globalData.token}`;
    }

    // 发起请求
    wx.request({
      url: fullUrl,
      method,
      data,
      header: requestHeader,
      success: (res) => {
        // 隐藏加载提示
        if (showLoading) {
          wx.hideLoading();
        }

        const { statusCode, data: responseData } = res;

        // HTTP状态码检查
        if (statusCode >= 200 && statusCode < 300) {
          // 业务逻辑检查
          if (responseData.code === 200) {
            resolve(responseData.data);
          } else {
            // 业务错误
            wx.showToast({
              title: responseData.message || '请求失败',
              icon: 'none',
              duration: 2000
            });
            reject(responseData);
          }
        } else if (statusCode === 401) {
          // 未授权，需要重新登录
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });

          // 清除登录信息
          app.logout();
          reject({ code: 401, message: '未授权' });
        } else {
          // 其他HTTP错误
          wx.showToast({
            title: `请求失败 (${statusCode})`,
            icon: 'none'
          });
          reject({ code: statusCode, message: '请求失败' });
        }
      },
      fail: (err) => {
        // 隐藏加载提示
        if (showLoading) {
          wx.hideLoading();
        }

        console.error('请求失败:', err);
        
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });

        reject(err);
      }
    });
  });
}

/**
 * GET请求
 */
function get(url, data = {}, options = {}) {
  return request({
    url,
    method: 'GET',
    data,
    ...options
  });
}

/**
 * POST请求
 */
function post(url, data = {}, options = {}) {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  });
}

/**
 * PUT请求
 */
function put(url, data = {}, options = {}) {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  });
}

/**
 * DELETE请求
 */
function del(url, data = {}, options = {}) {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  });
}

/**
 * 上传文件
 */
function uploadFile(url, filePath, formData = {}) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '上传中...',
      mask: true
    });

    const fullUrl = url.startsWith('http') ? url : `${app.globalData.apiBaseUrl}${url}`;

    wx.uploadFile({
      url: fullUrl,
      filePath,
      name: 'file',
      formData,
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        wx.hideLoading();

        const data = JSON.parse(res.data);

        if (data.code === 200) {
          resolve(data.data);
        } else {
          wx.showToast({
            title: data.message || '上传失败',
            icon: 'none'
          });
          reject(data);
        }
      },
      fail: (err) => {
        wx.hideLoading();
        
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });

        reject(err);
      }
    });
  });
}

module.exports = {
  request,
  get,
  post,
  put,
  del,
  uploadFile
};

